﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Sql;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using UniMana.Utils.Configs;

namespace UniMana.Win.Systems
{
//  Yêu cầu chạy backup và restore được
    //-- To allow advanced options to be changed.
//EXEC sp_configure 'show advanced options', 1
//GO
//-- To update the currently configured value for advanced options.
//RECONFIGURE
//GO
//-- To enable the feature.
//EXEC sp_configure 'xp_cmdshell', 1
//GO
//-- To update the currently configured value for this feature.
//RECONFIGURE
//GO
    public partial class FrmBackupDatabase : DevExpress.XtraEditors.XtraForm
    {
        Server m_srv;
        ServerConnection m_serverCon;
        SqlConnection m_sqlCon;
        DataTable m_dtBackupName;
        public FrmBackupDatabase()
        {
            InitializeComponent();
            m_dtBackupName = new DataTable();
            m_dtBackupName.Columns.Add("BackupDateTime", typeof(DateTime));
            m_dtBackupName.Columns.Add("BackupName", typeof(string));
            Connect();
            LoadBackupFile();
            
        }

        private bool Connect()
        {
            bool bSuccess = false;
            try
            {

                m_sqlCon = new SqlConnection(ServerConfig.ConnectionStringBackup);
                m_sqlCon.Open();
                m_serverCon = new ServerConnection(m_sqlCon);
                m_srv = new Server(m_serverCon);
               
                foreach (Database db in m_srv.Databases)
                {
                    cmbDatabaseList.Properties.Items.Add(db.Name);
                }

                bSuccess = true;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                bSuccess = false;
            }
            return bSuccess;
        }

        private void LoadBackupFile()
        {

            string strSql = "";

            strSql += "Execute xp_CmdShell @Cmd";
            SqlCommand command = m_sqlCon.CreateCommand();
            #region Mở xp_cmdshell
            string strEnableXP_CMDSHELL = "EXEC sp_configure 'show advanced options', 1";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();

            strEnableXP_CMDSHELL = "RECONFIGURE";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();

            strEnableXP_CMDSHELL = "EXEC sp_configure 'xp_cmdshell', 1";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();

            strEnableXP_CMDSHELL = "RECONFIGURE";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();
            #endregion

            command.CommandText = strSql;
            command.Parameters.Add("@Cmd", SqlDbType.NVarChar).Value = @"Dir D:\Database\ *.bak";
            //command.ExecuteNonQuery();
            SqlDataReader nReader = command.ExecuteReader();
            
            while (nReader.Read())
            {
                //nReader.Read();
                string strData = nReader[0].ToString();
                if (strData.Length > 3)
                {
                    if (strData.Substring(strData.Length - 3, 3) == "bak")
                    {
                        DateTime d ;
                        char []c = new [] {' '};
                        string[] temp = strData.Split(c, StringSplitOptions.RemoveEmptyEntries);
                        try
                        {
                             string[]  strdmy = temp[0].Split('/');
                             string date= strdmy[1]+"/"+strdmy[0]+"/"+strdmy[2] +" "+temp[1]+" "+temp[2];
                             d = DateTime.Parse(date);
                            // string strd = strData.Substring(0, 20);
                             string strBackupName = temp[temp.Length - 1];
                             DataRow dr = m_dtBackupName.NewRow();
                             dr["BackupDateTime"] = d;//strd;
                             dr["BackupName"] = strBackupName;
                             m_dtBackupName.Rows.Add(dr);
                        }
                        catch
                        { }
                    }
                }
            }

            nReader.Close();
            command.Dispose();
            m_sqlCon.Close();
            grcDatabaseRestore.DataSource = m_dtBackupName;
        }

        public void ProgressEventHandler(object sender, PercentCompleteEventArgs e)
        {
            this.progressBar1.Value = e.Percent;
        }

        private String GetTimestamp()
        {
            string strSql = "";
            string strData="";
            strSql += "select  convert(varchar(1000),SYSDATETIME())";
            m_sqlCon.Open();
            SqlCommand command = m_sqlCon.CreateCommand();
            command.CommandText = strSql;
            //command.Parameters.Add("@Cmd", SqlDbType.NVarChar).Value = @"Dir D:\Database\ *.bak";
            //command.ExecuteNonQuery();
            SqlDataReader nReader = command.ExecuteReader();
            if (nReader.Read())
            {
                strData = nReader[0].ToString();
            }
            nReader.Close();
            command.Dispose();
            m_sqlCon.Close();

            return strData;//.ToString("dd_MM_YYYY_HHmmss_fffffff");
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Backup bkp = new Backup();

            this.Cursor = Cursors.WaitCursor;
            
            try
            {
                
                string databaseName = this.cmbDatabaseList.Text;

                //var start = DateTime.Now;
                //do your operation here!
                //var timeSpan = GetTimestamp(start);
                string strDatetime = GetTimestamp();
                strDatetime = strDatetime.Replace("-", "_");
                strDatetime = strDatetime.Replace(".", "_");
                strDatetime = strDatetime.Replace(":", "");
                strDatetime = strDatetime.Replace(" ", "_");

                string fileName = @"D:\Database\" + databaseName + "_backup_" + strDatetime + ".bak";

                bkp.Action = BackupActionType.Database;
                bkp.Database = databaseName;
                bkp.Devices.AddDevice(fileName, DeviceType.File);
                //bkp.Incremental = ckeIncremental.Checked;
                this.progressBar1.Value = 0;
                this.progressBar1.Maximum = 100;
                this.progressBar1.Value = 10;

                bkp.PercentCompleteNotification = 10;
                bkp.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);

                bkp.SqlBackup(m_srv);
                MessageBox.Show("Database Backed Up To: " + fileName, "SMO");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
                this.progressBar1.Value = 0;
            }
        }

        private void btnDeleteFile_Click(object sender, EventArgs e)
        {
            DialogResult dlgResult = MessageBox.Show("Bạn có chắc xóa bản sao lưu " + grvDatabaseRestore.GetFocusedRowCellValue("BackupName").ToString() + " không ?", "Cảnh báo", MessageBoxButtons.OKCancel);
            if (dlgResult == System.Windows.Forms.DialogResult.OK)
            {
                if (m_dtBackupName.Rows.Count >= 100)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        string strFileName = grvDatabaseRestore.GetFocusedRowCellValue("BackupName").ToString(); //m_dtBackupName.Rows[i][1].ToString();
                        grvDatabaseRestore.DeleteSelectedRows();
                        DeleteFileServer(strFileName);
                    }
                }
            }
        }

        private void DeleteFileServer(string strFileName)
        {
            string strSql = "";
            m_sqlCon.Open();
            strSql += "Execute xp_CmdShell @Cmd";
            SqlCommand command = m_sqlCon.CreateCommand();
            command.CommandText = strSql;
            command.Parameters.Add("@Cmd", SqlDbType.NVarChar).Value = @"Del D:\Database\" + strFileName ;
            command.ExecuteNonQuery();
            command.Dispose();
            m_sqlCon.Close();
        }
    }
}